import { ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { computed, ref } from 'vue'
import { useUserStore } from "./user"
import { cartAddCart, cartDelCart, cartGetCartList } from "@/apis/cart"
export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  //state:
  const cartList = ref([])
  //action:
  // 清空购物车操作
  const clearCartList = () => cartList.value = []

  // 从后端获取购物车数据
  const getCartList = async () => {
    const res = await cartGetCartList()
    cartList.value = res.data.result
  }
  // 添加购物车操作
  const addCartList = async (goodsObj) => {
    // 添加购物车操作
    // 用户token存在走后端添加购物车的接口请求,重新获取cartList覆盖本地的数据.
    if (isLogin.value) {

      await cartAddCart({ skuId: goodsObj.skuId, count: goodsObj.count })
      getCartList()

    } else {

      // 用户没有的登录情况,进行的时本地购物车数据的添加.
      // 添加过的商品追加商品数量,未添加过的商品直接push
      const findItem = cartList.value.find(item => item.skuId === goodsObj.skuId)
      if (findItem) {
        // 添加过的商品
        findItem.count += goodsObj.count
      } else {
        // 未添加过的商品
        cartList.value.push(goodsObj)
      }
    }

  }

  // 通过id修改selcted的值
  const updateSelectedValById = async (skuId) => {

    const findItem = cartList.value.find(item => item.skuId === skuId)
    findItem.selected = !findItem.selected
  }

  // 删除购物车数据操作
  const delCart = async (skuId) => {
    if (isLogin.value) {

      await cartDelCart([skuId])
      ElMessage.success('成功除购物车商品')
      getCartList()
    } else {
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
      ElMessage.success('成功除购物车商品')
    }

  }

  // 全选acion
  const selectedAllgoods = (val) => {
    cartList.value.forEach(item => item.selected = val)
  }

  //gettes
  // 购物车商品总数量
  const goodsTotalCount = computed(() => {
    return cartList.value.reduce((sum, item) => {
      return sum + item.count
    }, 0)
  })

  // 购物车商品总价格
  const goodsTotalPrice = computed(() => {
    return cartList.value.reduce((sum, item) => {
      return sum + item.count * item.price
    }, 0)
  })

  // 购物车商品已选中的个数
  const goodsSelectedCount = computed(() => {
    let count = 0
    cartList.value.forEach(item => {
      if (item.selected) {
        count = item.count + count
      }
    })
    return count
  })

  // 获取已选中的商品总价
  const goodsSelctedTotalPrice = computed(() => {
    let price = 0
    cartList.value.forEach(item => {
      if (item.selected) {
        price = item.count * item.price + price
      }
    })
    return price
  })
  // 是否全选
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected === true)
  })
  return {
    cartList, addCartList, delCart, goodsTotalCount, goodsTotalPrice, goodsSelectedCount, isAll, goodsSelctedTotalPrice, updateSelectedValById, selectedAllgoods, clearCartList, getCartList
  }


}, { persist: true })
